package com.dididoctor.doctor.Utils;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;

import com.dididoctor.doctor.R;

import java.util.Random;

/**
 * 项目名称：Psd
 * 类描述：用户头像
 * 创建人：张强
 * 创建时间：2015/6/18 16:33
 * 修改人：
 * 修改时间：2015/6/18 16:33
 * 修改备注：
 */
public class UserHeadImage extends ImageView {
    private Bitmap bitmap = null;//要显示的头像
    private String text = null;//要显示的文字
    private int textColor = Color.WHITE;//文字颜色
    private int BgColor = Color.GRAY;//背景颜色
    private int radiusDegree = 50;//圆角度数
    private int textSize = (int) (getWidth() * 0.7f);
    private Paint paintBg = new Paint();
    private Paint pText = new Paint();
    private Integer[] UserHeadColor = {R.color.white, R.color.theme_score_1, R.color.theme_score_2, R.color.theme_score_3,
            R.color.theme_score_4, R.color.black, R.color.greenyellow, R.color.darkorchid, R.color.darker_gray};

    public UserHeadImage(Context context) {
        this(context, null);
    }

    public UserHeadImage(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.UserHeadImageStyle);
    }

    //构造
    public UserHeadImage(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        RectF oval3 = new RectF(0, 0, getWidth(), getWidth());// 设置个新的长方形


        if (this.bitmap != null) {
            canvas.drawRoundRect(oval3, radiusDegree, radiusDegree, paintBg);//第二个参数是x半径，第三个参数是y半径
            //创建一个指定大小的缩略图
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, getWidth(), getHeight());
            int top = 0;
            int left = 0;
            try {
                top = (getWidth() - bitmap.getWidth()) / 2;
                left = (getHeight() - bitmap.getHeight()) / 2;
            } catch (Exception e) {
            }
            canvas.drawBitmap(ImageUtil.getRoundedCornerBitmap(bitmap, this.radiusDegree), top, left, null);
        } else if (!Util.isEmpty(text)) {
            canvas.drawRoundRect(oval3, radiusDegree, radiusDegree, paintBg);//第二个参数是x半径，第三个参数是y半径
            /*paintBg.setStyle(Paint.Style.FILL);//充满
            paintBg.setColor(getBgColor());
			paintBg.setAntiAlias(true);// 设置画笔的锯齿效果
			RectF oval3 = new RectF(0, 0, getWidth(), getWidth());// 设置个新的长方形
			canvas.drawRoundRect(oval3, radiusDegree, radiusDegree, paintBg);//第二个参数是x半径，第三个参数是y半径*/
            this.drawText(canvas);
        }
        canvas.restore();
    }


    private void init(Context context, AttributeSet attrs) {
        final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.UserHeadImage);

        setUserHeadTextColor(attributes.getColor(R.styleable.UserHeadImage_setuserheadtext_color, Color.WHITE));
        setUserHeadBackgroundColor(attributes.getColor(R.styleable.UserHeadImage_setuserheadbackground_color,
                Color.GRAY));
        text = attributes.getString(R.styleable.UserHeadImage_setuserheadtext);
        setUserHeadText(text);
        setUserHeadTextSize((int) attributes.getDimension(R.styleable.UserHeadImage_setuserheadtextsize, 50f));
        setRadiusDegree((int) attributes.getDimension(R.styleable.UserHeadImage_setuserheadradiusdegree, 50f));
        attributes.recycle();
    }

    /**
     * @param canvas
     */
    private void drawText(Canvas canvas) {
        int x = getWidth();
        int y = getHeight();


        float tX = (x - getFontlength(pText, this.text)) / 2;
        float tY = (y - getFontHeight(pText)) / 2 + getFontLeading(pText);
        canvas.drawText(this.text, tX, tY, pText);
    }

    /**
     * 设置角度  10是正圆  50圆角
     */
    public void setRadiusDegree(int radiusDegree) {
        this.radiusDegree = radiusDegree;
    }

    /**
     * @return 返回指定笔和指定字符串的长度
     */
    public static float getFontlength(Paint paint, String str) {
        return paint.measureText(str);
    }

    /**
     * @return 返回指定笔的文字高度
     */
    public static float getFontHeight(Paint paint) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return fm.descent - fm.ascent;
    }

    /**
     * @return 返回指定笔离文字顶部的基准距离
     */
    public static float getFontLeading(Paint paint) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return fm.leading - fm.ascent;
    }


    /**
     * 设置Bitmap图片
     *
     * @param bitmap
     */
    @Override
    public void setImageBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        postInvalidate();
    }

    /**
     * 设置资源图片
     *
     * @param res
     */
    public void setImageResource(int res) {
        Drawable drawable = getResources().getDrawable(res);
        this.bitmap = ImageUtil.drawableToBitmap(drawable);
        postInvalidate();
    }


    /**
     * 设置用户文字大小
     *
     * @param textSize
     */
    public void setUserHeadTextSize(int textSize) {
        Context c = getContext();
        Resources r;

        if (c == null)
            r = Resources.getSystem();
        else
            r = c.getResources();
        int size = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, textSize, r.getDisplayMetrics());
        this.textSize = textSize;

//        updateUserHeadTextColor();
    }


    /**
     * 设置用户文字
     *
     * @param text
     */
    public void setUserHeadText(String text) {
        if (Util.isEmpty(text)) {
            return;
        }
        if (text.length() > 1) {
            text = text.substring(0, 1);
        }
        this.text = text;
//        updateUserHeadTextColor();
    }

    /**
     * 设置用户头像背景颜色
     *
     * @param color 色值
     */
    public void setUserHeadBackgroundColor(int color) {

        this.BgColor = color;
//        updateUserHeadBackgroundColor();
    }

    /**
     * 设置背景颜色画笔
     */
    private void updateUserHeadBackgroundColor() {

        paintBg.setStyle(Paint.Style.FILL);//充满
        paintBg.setColor(this.BgColor);
        paintBg.setDither(true);//定是否使用图像抖动处理
        paintBg.setStyle(Paint.Style.FILL_AND_STROKE);
        paintBg.setAntiAlias(true);// 设置画笔的锯齿效果
    }

    /**
     * 设置用户头像随机背景颜色
     *
     * @param
     */
    public void setRandomUserHeadBackgroundAndTextColor() {
        int length = UserHeadColor.length;
        Random random = new Random();
        int x = random.nextInt(length - 1);
        int y = random.nextInt(length - 1);
        if (x == y) {
            this.BgColor = R.color.darker_gray;
            this.textColor = R.color.white;

        } else {
            this.BgColor = getResources().getColor(UserHeadColor[x]);
            this.textColor = getResources().getColor(UserHeadColor[y]);
        }

        if (x == 0) {
            this.BgColor = R.color.darker_gray;
        }

//        updateUserHeadBackgroundColor();
//        updateUserHeadTextColor();
    }

    /**
     * 显示绘画头像
     */
    public void UserHeadShow() {
        updateUserHeadBackgroundColor();
        updateUserHeadTextColor();
        invalidate();
    }

    /**
     * 设置用户头像的文字颜色
     *
     * @param color 色值
     */
    public void setUserHeadTextColor(int color) {
        this.textColor = color;
//        updateUserHeadTextColor();
    }

    /**
     * 设置文字颜色的画笔
     */
    private void updateUserHeadTextColor() {

        this.pText.setColor(textColor);
        //p.setTypeface(font);
        this.pText.setAntiAlias(true);//去除锯齿
        this.pText.setFilterBitmap(true);//对位图进行滤波处理
        this.pText.setTextSize(this.textSize);
        this.pText.setStyle(Paint.Style.FILL_AND_STROKE);
//        invalidate();

    }

    /**
     * 根据屏幕系数比例获取文字大小
     *
     * @return
     */
    private static float scalaFonts(int size) {
        //暂未实现
        return size;
    }
}
